//
//  CycleCalendarView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/18.
//


import SwiftUI


struct CycleCalendarView: View {
    @EnvironmentObject var appState: AppState
    @State private var currentDate = Date()
    private let calendar = Calendar.current
    
    var body: some View {
        VStack {
            CustomNavigationBar(rightImageName: nil, title: "生理周期") {}
            VStack(spacing: 24) {
                HStack() {
                    HStack {
                        Circle()
                            .fill(Color(hex: "#FF8DAC"))
                            .frame(width: 12, height: 12)
                        Text("预测生理期").font(.system(size: 12)).foregroundStyle(.white)
                    }
                    Spacer()
                    HStack {
                        Circle()
                            .fill(Color(hex: "#F352BD"))
                            .frame(width: 12, height: 12)
                        Text("生理期").font(.system(size: 12)).foregroundStyle(.white)
                    }
                    Spacer()
                    HStack {
                        Circle()
                            .fill(Color(hex: "#797CF7"))
                            .frame(width: 12, height: 12)
                        Text("排卵期").font(.system(size: 12)).foregroundStyle(.white)
                    }
                    Spacer()
                    HStack {
                        Circle()
                            .fill(Color(hex: "#DB79F7"))
                            .frame(width: 12, height: 12)
                        Text("排卵日").font(.system(size: 12)).foregroundStyle(.white)
                    }
                }
                .padding(.horizontal,20)
                .padding(.top,24)
                MonthHeaderView(currentDate: $currentDate)
                    .padding(.horizontal,20)
                WeekdayHeaderView()
                    .padding(.horizontal,20)
                MonthGridView(currentDate: $currentDate)
                    .padding(.horizontal,20)
            }
            .background(Color(hex: "##1E1E1E"))
            .cornerRadius(16)
            .padding(.horizontal,12)
            .padding(.top,12)
            
            Spacer().frame(height: 16)
            
            HStack (spacing: 12) {
                Image("sltz")
                    .resizable()
                    .frame(width: 32,height: 32)
                    .padding(.leading,20)
                Text("通知提醒").font(.system(size: 16)).foregroundStyle(.white)
                Spacer()
                Image("xiangyou")
                    .resizable()
                    .frame(width: 16,height: 16)
                    .padding(.trailing,20)
                    .onTapGesture {
                        appState.navigateTo(.cycleCalendarNotify)
                    }
            }
            .frame(height: 56)
            .background(Color(hex: "##1E1E1E"))
            .cornerRadius(16)
            .padding(.horizontal,12)
            Spacer().frame(height: 12)
            HStack (spacing: 12) {
                Image("slsz")
                    .resizable()
                    .frame(width: 32,height: 32)
                    .padding(.leading,20)
                Text("生理周期设置").font(.system(size: 16)).foregroundStyle(.white)
                Spacer()
                Image("xiangyou")
                    .resizable()
                    .frame(width: 16,height: 16)
                    .padding(.trailing,20)
                    .onTapGesture {
                        appState.navigateTo(.cycleCalendarSetting)
                    }
            }
            .frame(height: 56)
            .background(Color(hex: "##1E1E1E"))
            .cornerRadius(16)
            .padding(.horizontal,12)
            Spacer()
            
            
            
        }
        .navigationBarHidden(true)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
    }
}

struct MonthHeaderView: View {
    @Binding var currentDate: Date
    var body: some View {
        HStack {
            Button(action: { self.changeMonth(by: -1) }) {
                Image("left")
            }
            Spacer()
            Text(currentDate.monthYearString)
                .font(.system(size: 16))
                .foregroundStyle(.white)
            Spacer()
            
            Button(action: { self.changeMonth(by: 1) }) {
                Image("right")
            }
        }
    }
    
    private func changeMonth(by value: Int) {
        currentDate = Calendar.current.date(byAdding: .month, value: value, to: currentDate)!
    }
}

struct WeekdayHeaderView: View {
    private let weekdays = ["日", "一", "二", "三", "四", "五", "六"]
    
    var body: some View {
        HStack(spacing: 0) {
            ForEach(weekdays, id: \.self) { day in
                Text(day)
                    .font(.system(size: 14))
                    .foregroundStyle(.white)
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 8)
            }
        }
    }
}

struct MonthGridView: View {
    @Binding var currentDate: Date
    private let calendar = Calendar.current
    
    var body: some View {
        let days = generateDaysInMonth()
        
        LazyVGrid(columns: Array(repeating: GridItem(spacing: 0),count: 7)) {
            ForEach(days, id: \.self) { date in
                DayView(date: date, isCurrentMonth: calendar.isDate(date, equalTo: currentDate, toGranularity: .month))
            }
        }
    }
    
    private func generateDaysInMonth() -> [Date] {
        guard let monthInterval = calendar.dateInterval(of: .month, for: currentDate),
              let monthFirstWeek = calendar.dateInterval(of: .weekOfMonth, for: monthInterval.start),
              let monthLastWeek = calendar.dateInterval(of: .weekOfMonth, for: monthInterval.end - 1) else {
            return []
        }
        
        let startDate = monthFirstWeek.start
        let endDate = monthLastWeek.end
        var currentDate = startDate
        var dates = [Date]()
        
        while currentDate < endDate {
            dates.append(currentDate)
            currentDate = calendar.date(byAdding: .day, value: 1, to: currentDate)!
        }
        
        return dates
    }
}

struct DayView: View {
    let date: Date
    let isCurrentMonth: Bool
    @State private var plr = {
        guard let date = TimestampHelper.convert("2025-07-26") else {
            return Date()
        }
        return date
    }
    @State private var ycslq: [Date] = {
        var ss:[Date] = []
        guard let date = TimestampHelper.convert("2025-07-1") else {
            return []
        }
        guard let date1 = TimestampHelper.convert("2025-07-2") else {
            return []
        }
        guard let date2 = TimestampHelper.convert("2025-07-3") else {
            return []
        }
        
        ss.append(date)
        ss.append(date1)
        ss.append(date2)
        return ss
    }()
    
    @State private var slq: [Date] = {
        var ss:[Date] = []
        guard let date = TimestampHelper.convert("2025-07-9") else {
            return []
        }
        guard let date1 = TimestampHelper.convert("2025-07-10") else {
            return []
        }
        guard let date2 = TimestampHelper.convert("2025-07-11") else {
            return []
        }
        guard let date3 = TimestampHelper.convert("2025-07-12") else {
            return []
        }
        ss.append(date)
        ss.append(date1)
        ss.append(date2)
        ss.append(date3)
        return ss
    }()
    
    @State private var plq: [Date] = {
        var ss:[Date] = []
        guard let date = TimestampHelper.convert("2025-07-14") else {
            return []
        }
        guard let date1 = TimestampHelper.convert("2025-07-15") else {
            return []
        }
        guard let date2 = TimestampHelper.convert("2025-07-16") else {
            return []
        }
        guard let date3 = TimestampHelper.convert("2025-07-17") else {
            return []
        }
        ss.append(date)
        ss.append(date1)
        ss.append(date2)
        ss.append(date3)
        return ss
    }()
    

    var body: some View {
        HStack {
            if Calendar.current.isDate(date, inSameDayAs:plr()) {
                Text("\(Calendar.current.component(.day, from: date))")
                    .frame(maxWidth: .infinity, minHeight: 40)
                    .foregroundColor(.white)
                    .background(
                        Circle()
                            .fill(Color(hex: "#DB79F7"))
                            .frame(width: 40, height: 40)
                    )
            } else {
                Text("\(Calendar.current.component(.day, from: date))")
                    .frame(maxWidth: .infinity, minHeight: 40)
                    .foregroundColor(.white)
                    .background(
                        ycslq.contains(date) ? Color(hex: "#FF8DAC"):
                          slq.contains(date) ? Color(hex: "#F352BD"):
                          plq.contains(date) ? Color(hex: "#797CF7"):
                                .clear
                    )
                    .clipShape(
                        .rect(
                            topLeadingRadius:
                                Calendar.current.isDate(date, inSameDayAs: ycslq.first ?? Date()) ? 20:
                                Calendar.current.isDate(date, inSameDayAs: slq.first ?? Date()) ?   20:
                                Calendar.current.isDate(date, inSameDayAs: plq.first ?? Date()) ?   20:
                                       0,
                            bottomLeadingRadius:
                                Calendar.current.isDate(date, inSameDayAs: ycslq.first ?? Date()) ? 20:
                                Calendar.current.isDate(date, inSameDayAs: slq.first ?? Date()) ?   20:
                                Calendar.current.isDate(date, inSameDayAs: plq.first ?? Date()) ?   20:
                                     0,
                            bottomTrailingRadius: Calendar.current.isDate(date, inSameDayAs: ycslq.last ?? Date()) ? 20 :
                                Calendar.current.isDate(date, inSameDayAs: slq.last ?? Date()) ? 20:
                                Calendar.current.isDate(date, inSameDayAs: plq.last ?? Date()) ? 20:
                                0,
                            topTrailingRadius: Calendar.current.isDate(date, inSameDayAs: ycslq.last ?? Date()) ? 20 :
                                Calendar.current.isDate(date, inSameDayAs: slq.last ?? Date()) ? 20:
                                Calendar.current.isDate(date, inSameDayAs: plq.last ?? Date()) ? 20:
                                0
                        )
                    )
            }
        }
        
    }
}

extension Date {
    var monthYearString: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月"
        return formatter.string(from: self)
    }
    
    var isToday: Bool {
        Calendar.current.isDateInToday(self)
    }
}
